<template>
  <div class="purchase-order-create">
    <div class="header">
      <h2>新建进货单</h2>
    </div>

    <el-form :model="orderForm" label-width="100px">
      <!-- 经销商选择 -->
      <el-form-item label="经销商" required>
        <el-select 
          v-model="orderForm.dealer_id" 
          placeholder="请选择经销商"
          filterable
          :loading="dealersLoading"
        >
          <el-option 
            v-for="dealer in dealers" 
            :key="dealer.id" 
            :label="dealer.name" 
            :value="dealer.id" 
          />
        </el-select>
      </el-form-item>

      <!-- 商品添加 -->
      <el-form-item label="添加商品">
        <div class="item-input">
          <el-input
            v-model="itemForm.code"
            placeholder="输入ISBN/商品编码"
            @keyup.enter="searchItem"
          />
          <el-button type="primary" @click="searchItem">搜索</el-button>
        </div>
      </el-form-item>

      <!-- 商品列表 -->
      <el-table :data="orderForm.items" style="width: 100%">
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            {{ row.type === 'book' ? '图书' : '商品' }}
          </template>
        </el-table-column>
        <el-table-column prop="unit_price" label="单价">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.unit_price" 
              :precision="2" 
              :step="0.01"
              @change="calculateItemTotal(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.quantity" 
              :min="1" 
              @change="calculateItemTotal(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="折扣">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.discount" 
              :precision="2" 
              :step="0.01"
              :min="0"
              :max="1"
              @change="calculateItemTotal(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="小计">
          <template #default="{ row }">
            ￥{{ row.total_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ $index }">
            <el-button 
              type="danger" 
              size="small" 
              @click="removeItem($index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input 
          v-model="orderForm.notes" 
          type="textarea" 
          rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>

      <!-- 总计 -->
      <div class="total">
        <h3>总金额：￥{{ totalAmount.toFixed(2) }}</h3>
      </div>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitOrder" :loading="submitting">
          提交订单
        </el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import PurchaseOrderService from '@/api/purchaseOrderService'
import DealerService from '@/api/dealerService'
import BookService from '@/api/bookService'
import GoodsService from '@/api/goodsService'

const router = useRouter()
const dealers = ref([])
const submitting = ref(false)
const dealersLoading = ref(false)

const orderForm = reactive({
  dealer_id: '',
  items: [],
  notes: ''
})

const itemForm = reactive({
  code: ''
})

const totalAmount = computed(() => {
  return orderForm.items.reduce((sum, item) => sum + item.total_price, 0)
})

// 获取经销商列表
async function fetchDealers() {
  dealersLoading.value = true
  try {
    console.log('Fetching dealers in PurchaseOrderCreate...')
    const response = await DealerService.getAllDealers()
    console.log('Dealers response:', response)
    if (response.data && Array.isArray(response.data)) {
      dealers.value = response.data
      console.log('Dealers loaded:', dealers.value)
    } else {
      throw new Error('Invalid dealers data format')
    }
  } catch (error) {
    console.error('Error fetching dealers:', error)
    ElMessage.error('获取经销商列表失败: ' + (error.response?.data?.error || error.message))
    dealers.value = [] // 确保dealers是一个空数组而不是undefined
  } finally {
    dealersLoading.value = false
  }
}

// 搜索商品
async function searchItem() {
  if (!itemForm.code) {
    ElMessage.warning('请输入ISBN或商品编码')
    return
  }

  try {
    let item = null
    // 先搜索图书
    try {
      const response = await BookService.getBookByISBN(itemForm.code)
      item = {
        type: 'book',
        id: response.data.isbn,
        name: response.data.title,
        unit_price: response.data.price,
        quantity: 1,
        discount: response.data.purchase_discount || 1
      }
    } catch {
      // 如果不是图书，搜索商品
      const response = await GoodsService.getGoodsByCode(itemForm.code)
      item = {
        type: 'goods',
        id: response.data.code,
        name: response.data.name,
        unit_price: response.data.purchase_price,
        quantity: 1,
        discount: 1
      }
    }

    if (item) {
      // 检查是否已存在
      const existingIndex = orderForm.items.findIndex(i => 
        i.type === item.type && i.id === item.id
      )

      if (existingIndex >= 0) {
        orderForm.items[existingIndex].quantity += 1
        calculateItemTotal(orderForm.items[existingIndex])
      } else {
        calculateItemTotal(item)
        orderForm.items.push(item)
      }

      itemForm.code = ''
    }
  } catch (error) {
    console.error('Error searching item:', error)
    ElMessage.error('未找到商品')
  }
}

// 计算商品小计
function calculateItemTotal(item) {
  item.total_price = item.quantity * item.unit_price * item.discount
}

// 移除商品
function removeItem(index) {
  orderForm.items.splice(index, 1)
}

// 提交订单
async function submitOrder() {
  if (!orderForm.dealer_id) {
    ElMessage.warning('请选择经销商')
    return
  }

  if (orderForm.items.length === 0) {
    ElMessage.warning('请添加商品')
    return
  }

  submitting.value = true
  try {
    await PurchaseOrderService.createOrder(orderForm)
    ElMessage.success('订单创建成功')
    router.push('/purchase-orders')
  } catch (error) {
    console.error('Error creating order:', error)
    ElMessage.error('订单创建失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  console.log('PurchaseOrderCreate mounted, fetching dealers...')
  fetchDealers()
})
</script>

<style scoped>
.purchase-order-create {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.item-input {
  display: flex;
  gap: 10px;
}

.total {
  text-align: right;
  margin: 20px 0;
}

.total h3 {
  color: #409EFF;
  font-size: 20px;
}
</style> 